package com.antler.codelua.view;

import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Build;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.widget.RelativeLayout;

public abstract class BaseFloatView extends RelativeLayout {
    protected boolean mIsAddWm = false;
    protected WindowManager mWindowManager;
    protected WindowManager.LayoutParams mParams;

    public BaseFloatView(Context context) {
        super(context);
        init();
    }

    public BaseFloatView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public BaseFloatView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    protected void init() {
        initView();
    }

    protected void initView() {
    }

    protected void actionDown(MotionEvent event) {
    }

    protected void actionUp(MotionEvent event) {
    }

    protected void actionMove(MotionEvent event) {
    }

    public void addFloat(int x, int y) {
        if (!mIsAddWm) {
            mWindowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
            mParams = new WindowManager.LayoutParams();
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT || Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                mParams.type = WindowManager.LayoutParams.TYPE_PHONE;
            } else {
                mParams.type = WindowManager.LayoutParams.TYPE_TOAST;
            }

            mParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
            mParams.format = PixelFormat.RGBA_8888;

            mParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
            mParams.height = WindowManager.LayoutParams.WRAP_CONTENT;

            mParams.x = x;
            mParams.y = y;

            setLayoutParams(mParams);

            mWindowManager.addView(this, mParams);

            mIsAddWm = true;
        }
    }

    public void removeFloat() {
        if (mWindowManager != null && mIsAddWm) {
            mWindowManager.removeView(this);
        }

        mIsAddWm = false;
    }

    protected void updateViewLayout() {
        if (mWindowManager != null && mIsAddWm && mParams != null) {
            mWindowManager.updateViewLayout(this, mParams);
        }
    }

    protected void updateViewPosition(int x, int y) {
        if (mParams != null) {
            mParams.x = x;
            mParams.y = y;
        }
        updateViewLayout();
    }


    protected void offsetViewPosition(int xOffset, int yOffset) {
        if (mParams != null) {
            mParams.x += xOffset;
            mParams.y += yOffset;
        }
        updateViewLayout();
    }
}
